﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using IMC100APIDLL;

namespace PrgRun
{
    public partial class UcH5U_PLC : UserControl
    {
        int nNetId = 1;      
        bool m_bConnected = false;
        public UcH5U_PLC()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            cmbElemType.SelectedIndex = 0;
            cmbDataType.SelectedIndex = 0;
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            //缓冲区。读取整型字元件则一个元件占两个byte，位元件则占一个byte。例如读取D元件500个，则缓冲区大小为1000以上
            byte[] pBuf = new byte[16000];
            int nStartAddr = Convert.ToInt32(txtStartAddr.Text);
            int nCount = Convert.ToInt32(txtCount.Text);
            bool bIsWord = false;//是否字元件
            SoftElemType ElemType = SoftElemType.REGI_H5U_Y;
            if (cmbElemType.Text == "Y")
            {
                ElemType = SoftElemType.REGI_H5U_Y;
            }
            else if (cmbElemType.Text == "X")
            {
                ElemType = SoftElemType.REGI_H5U_X;
            }
            else if (cmbElemType.Text == "S")
            {
                ElemType = SoftElemType.REGI_H5U_S;
            }
            else if (cmbElemType.Text == "M")
            {
                ElemType = SoftElemType.REGI_H5U_M;
            }
            else if (cmbElemType.Text == "B")
            {
                ElemType = SoftElemType.REGI_H5U_B;
            }
            else if (cmbElemType.Text == "D")
            {
                bIsWord = true;
                ElemType = SoftElemType.REGI_H5U_D;//REGI_H3U_DW,REGI_H5U_D
            }
            else if (cmbElemType.Text == "R")
            {
                bIsWord = true;
                ElemType = SoftElemType.REGI_H5U_R;
            }            
            int nRet = IMC100API.H5u_Read_Soft_Elem_Lock(ElemType, nStartAddr, nCount, pBuf, nNetId);
            if (nRet != 1)
            {
                //txtMsg.Text = txtMsg.Text + DateTime.Now.ToString() + "：ErrorCode " + nRet.ToString() + "\r\n";
                MessageBox.Show(nRet.ToString());
                //m_bKeepRead = false;
                return;
            }
            string strData = "";
            int nDataType = cmbDataType.SelectedIndex;
            if (nDataType == 1 || nDataType == 2)
            {
                nCount = nCount / 2;
            }
            for (int i = 0; i < nCount; i++)
            {
                if (bIsWord)
                {
                    if (nDataType == 0)//16位整形
                    {
                        byte[] databuf = new byte[2] { 0, 0 };
                        databuf[0] = pBuf[i * 2];
                        databuf[1] = pBuf[i * 2 + 1];
                        int iTemp = BitConverter.ToInt16(databuf, 0);
                        strData = strData + iTemp.ToString() + " ";
                        continue;
                    }
                    else if (nDataType == 1)//读取32位整形
                    {
                        byte[] databuf = new byte[4] { 0, 0, 0, 0 };
                        databuf[0] = pBuf[i * 4];
                        databuf[1] = pBuf[i * 4 + 1];
                        databuf[2] = pBuf[i * 4 + 2];
                        databuf[3] = pBuf[i * 4 + 3];
                        int iTemp = BitConverter.ToInt32(databuf, 0);
                        strData = strData + iTemp.ToString() + " ";
                        continue;
                    }
                    else if (nDataType == 2)//读取浮点型
                    {
                        byte[] databuf = new byte[4] { 0, 0, 0, 0 };
                        databuf[0] = pBuf[i * 4];
                        databuf[1] = pBuf[i * 4 + 1];
                        databuf[2] = pBuf[i * 4 + 2];
                        databuf[3] = pBuf[i * 4 + 3];
                        float fTemp = BitConverter.ToSingle(databuf, 0);
                        strData = strData + fTemp.ToString() + " ";
                        continue;
                    }
                }
                else
                {
                    int nVal = 0;
                    nVal = pBuf[i];
                    strData = strData + nVal.ToString() + " ";
                }
            }
            txtData.Text = strData;
            //txtMsg.Text = txtMsg.Text + DateTime.Now.ToString() + "读取成功！\r\n";
            txtMsg.AppendText(DateTime.Now.ToString() + "读取成功！\r\n");
            txtMsg.ScrollToCaret();
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            byte[] pBuf = new byte[16000];
            int nStartAddr = Convert.ToInt32(txtStartAddr.Text);
            int nCount = Convert.ToInt32(txtCount.Text);
            bool bIsWord = false;//是否字元件

            SoftElemType ElemType = SoftElemType.REGI_H5U_Y;
            if (cmbElemType.Text == "Y")
            {
                ElemType = SoftElemType.REGI_H5U_Y;
            }
            else if (cmbElemType.Text == "X")
            {
                ElemType = SoftElemType.REGI_H5U_X;
            }
            else if (cmbElemType.Text == "S")
            {
                ElemType = SoftElemType.REGI_H5U_S;
            }
            else if (cmbElemType.Text == "M")
            {
                ElemType = SoftElemType.REGI_H5U_M;
            }
            else if (cmbElemType.Text == "B")
            {
                ElemType = SoftElemType.REGI_H5U_B;
            }
            else if (cmbElemType.Text == "D")
            {
                bIsWord = true;
                ElemType = SoftElemType.REGI_H5U_D;//REGI_H3U_DW,REGI_H5U_D
            }
            else if (cmbElemType.Text == "R")
            {
                bIsWord = true;
                ElemType = SoftElemType.REGI_H5U_R;
            }

            string[] arr = txtData.Text.Split(' ');

            int nDataType = cmbDataType.SelectedIndex;
            GetDataFromUI(pBuf, arr, bIsWord, nDataType);
            int nRet = IMC100API.H5u_Write_Soft_Elem_Lock(ElemType, nStartAddr, nCount, pBuf, nNetId);
            if (nRet != 1)
            {
                txtMsg.AppendText(DateTime.Now.ToString() + "：ErrorCode " + nRet.ToString() + "\r\n");
                txtMsg.ScrollToCaret();
                MessageBox.Show("写入失败");
            }
            else
            {
                txtMsg.AppendText(DateTime.Now.ToString() + "写入成功！\r\n");
                txtMsg.ScrollToCaret();
            }
        }

        private void GetDataFromUI(byte[] pBuf, string[] arr, bool bIsWord, int nDataType)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == string.Empty)
                {
                    break;
                }
                double nVal = Convert.ToDouble(arr[i]);
                if (bIsWord)
                {
                    if (nDataType == 0)//16位整形
                    {
                        int idata = Convert.ToInt16(arr[i]);
                        byte[] dataBuf = new byte[2] { 0, 0 };
                        dataBuf = BitConverter.GetBytes(idata);
                        pBuf[2 * i] = dataBuf[0];
                        pBuf[2 * i + 1] = dataBuf[1];
                    }
                    else if (nDataType == 1)//32位整形
                    {
                        int idata = Convert.ToInt32(arr[i]);
                        byte[] dataBuf = new byte[4] { 0, 0, 0, 0 };
                        dataBuf = BitConverter.GetBytes(idata);
                        pBuf[4 * i] = dataBuf[0];
                        pBuf[4 * i + 1] = dataBuf[1];
                        pBuf[4 * i + 2] = dataBuf[2];
                        pBuf[4 * i + 3] = dataBuf[3];
                    }
                    else if (nDataType == 2)//浮点数
                    {
                        float fdata = Convert.ToSingle(arr[i]);
                        byte[] dataBuf = new byte[4] { 0, 0, 0, 0 };
                        dataBuf = BitConverter.GetBytes(fdata);
                        pBuf[4 * i] = dataBuf[0];
                        pBuf[4 * i + 1] = dataBuf[1];
                        pBuf[4 * i + 2] = dataBuf[2];
                        pBuf[4 * i + 3] = dataBuf[3];
                    }
                }
                else
                {
                    pBuf[i] = (byte)nVal;
                }
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {           
            if(btnConnect.Text =="连接")
            {
                bool result = IMC100API.H5u_Connect(txtIP.Text, nNetId);
                if (result == true)
                {
                    m_bConnected = true;
                    label4.Text = "已连接";
                    txtMsg.Text = txtMsg.Text + DateTime.Now.ToString() + "连接PLC！\r\n";
                    btnConnect.Text = "断开连接";
                    timer1.Start();
                }
                else
                {
                    txtMsg.AppendText("连接失败");
                }
            }
            else
            {
                timer1.Stop();
                bool result = IMC100API.Exit_ETH(nNetId);
                if (result == true)
                {
                    btnConnect.Text = "连接";
                    txtMsg.Text = "断开连接成功";
                }
                else
                {
                    txtMsg.AppendText("断开连接失败");
                }
            }
           
        }
        private void InitLabel()
        {
            string strLbl = "label";
            for (int i = 0; i < 16; i++)
            {
                strLbl = string.Format($"lbl_{i}");
                Label M = (Label)Controls[strLbl];
                if(i<8)
                   M.Text = $" X{i}";
                else
                   M.Text = $"X{i-8+10}";
            }
            for (int i = 0; i < 16; i++)
            {
                strLbl = string.Format($"lbl_Y{i}");
                Label M = (Label)Controls[strLbl];
                if (i < 8)
                    M.Text = $" Y{i}";
                else
                    M.Text = $"Y{i - 8 + 10}";
            }
        }
        private void Y_OUTPUT(object sender, EventArgs e)
        {
            Label M = (Label)sender;
            int DO = Convert.ToInt16(M.Text.Replace("Y", ""));
            byte[] pBuf = new byte[16000];
            int nRet = IMC100API.H5u_Write_Soft_Elem_Lock(SoftElemType.REGI_H5U_Y, DO, 1, pBuf, nNetId);
            if (nRet != 1)
            {
                txtMsg.AppendText(DateTime.Now.ToString() + "：ErrorCode " + nRet.ToString() + "\r\n");
                txtMsg.ScrollToCaret();
                MessageBox.Show("写入失败");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] pBuf = new byte[16000];
            int nRet = IMC100API.H5u_Read_Soft_Elem_Lock(SoftElemType.REGI_H5U_Y, 0, 16, pBuf, nNetId);
            if (nRet == 1)
            {
                for (int i = 0; i < 16; i++)
                {
                    int nVal = 0;
                    nVal = pBuf[i];
                    Label M = (Label)Controls[$"lbl_Y{i}"];
                    M.BackColor = nVal == 1?Color.Green:Color.Gray;
                }
            }
            nRet = IMC100API.H5u_Read_Soft_Elem_Lock(SoftElemType.REGI_H5U_X, 0, 16, pBuf, nNetId);
            if (nRet == 1)
            {
                for (int i = 0; i < 16; i++)
                {
                    int nVal = 0;
                    nVal = pBuf[i];
                    Label M = (Label)Controls[$"lbl_{i}"];
                    M.BackColor = nVal == 1 ? Color.Green : Color.Gray;
                }
            }
        }

        private void UcH5U_PLC_Load(object sender, EventArgs e)
        {
            InitLabel();
        }
    }
}
